package cn.autoOffice.service.impl;
/*
 *功能说明：考勤服务实现层
 *@author 皮永浪
 *@Date 2023/3/27 11:30
 */

import cn.autoOffice.bean.pojo.Check;
import cn.autoOffice.mapper.CheckMapper;
import cn.autoOffice.service.CheckService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class CheckServiceImpl implements CheckService{

    @Autowired
    @Resource
    private CheckMapper checkMapper;

    //添加考勤信息
    @Override
    public boolean addCheckInfo(Check check) {
        return checkMapper.addCheckInfo(check);
    }

    //查询考勤信息
    @Override
    public List<Check> findAllChecks() {
        return checkMapper.findAllChecks();
    }

    /**
     * @ClassName TimedTaskService
     * @Description 定时任务（删除或者查询) 定时器
     * @Author 皮永浪
     * @Date 2023/3/30 17:17
     * @Version 1.0
     */

    Logger logger = LoggerFactory.getLogger(CheckServiceImpl.class);
    //每天晚上12:00定时删除30天之前的数据
    @Scheduled(cron = "0 0 0 * * ?")
    public void scheduled() {
        Date newDate=new Date();
        LocalDate deleteDate=getDate(newDate,30);
        try{
            checkMapper.deleteByDate(deleteDate);
        }catch (Exception e){
            logger.error("删除前天的考勤数据！"+e.getMessage());
        }

    }

    /**
     * @Description: 获取时间
     * @param: [now, days]
     * @return: java.lang.String
     */

    public static LocalDate getDate(Date now, int days){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.DATE, -days);
        Date deleteDate=calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateString=sdf.format(deleteDate);
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate= LocalDate.parse(dateString,fmt);
        return localDate;
    }
}
